<!Doctype html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Document</title>
</head>
<style>

.big{
    width: 400px;
    height: 400px;
    border:1px solid #000;
    position: relative;
    margin:auto;
}    
.small{
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: red;
}
</style>
<body>
<div class="big">
    <div class="small"></div>
</div>
</body>
<script>
var big = document.querySelector(".big");
var small = document.querySelector(".small");
small.onmousedown = function(e){
    var e = e || window.event;
    var x = e.offsetX;
    var y = e.offsetY;
    big.onmousemove = function(e){
        var e = e || window.event;
        // offsetX和offsetY本意是获取光标在事件源上的位置坐标，但是实际上获取是当前光标所在div上的位置
        // var x1 = e.offsetX
        // var y1 = e.offsetY;

        var x1 = e.clientX;
        var y1 = e.clientY;
        // console.log(x1);
        var l = x1 - x - big.offsetLeft;
        // console.log(l);
        var t = y1 - y - big.offsetTop;
        if(l<=0){
            l=0
        }
        if(t<=0){
            t=0
        }
        if(l>=big.clientWidth - small.clientWidth){
            l = big.clientWidth - small.clientWidth
        }
        if(t>=big.clientHeight - small.clientHeight){
            t = big.clientHeight - small.clientHeight
        }
        small.style.left = l + "px"
        small.style.top = t + "px"
    }
}

document.onmouseup = function(){
    big.onmousemove = null
}
</script>
</html>